import { useEffect, useState } from 'react'
import { interval, Subject, Subscription } from 'rxjs'
import { debounceTime, map, switchMap, tap } from 'rxjs/operators'
import Taro, { FC, usePullDownRefresh, useReachBottom, useReady } from '@tarojs/taro'
import { AtCheckbox } from 'taro-ui'
import { CheckboxOption } from 'taro-ui/types/checkbox'
import { View } from '@tarojs/components'
import { arrayRemove } from '@datorama/akita'
import { useMsgsFacade } from '@/hooks/useMsgsFacade'

import "taro-ui/dist/style/components/button.scss" // 按需引入 
import "taro-ui/dist/style/components/checkbox.scss"
import "taro-ui/dist/style/components/icon.scss"
import "taro-ui/dist/style/components/radio.scss"
import './index.scss'

//评论批量放行
export const ChatLIst: FC = () => {

  const [msgsFacade] = useMsgsFacade();

  //勾选的内容
  const [checkedList, setCheckedList] = useState<string[]>([]);
  //显示的所有内容
  const [checkboxes, setCheckboxes] = useState<CheckboxOption<any>[]>([]);

  //多播对象，用于按钮点击传值
  const initSubject = () => new Subject<any>();
  // 初始化按钮接收参数subject
  const [emitter, setEmitter] = useState(initSubject);

  //点击选择
  const handleChange = (value) => {
    console.log('选中的数据：', value)
    setCheckedList(value)
  }

  //全选
  const selectAll = () => {
    let newCheckedList = []
    for (let index = 0; index < checkboxes.length; index++) {
      const element = checkboxes[index];
      newCheckedList = newCheckedList.concat(element.value)
      setCheckedList(newCheckedList)
    }
  }

  //反选
  const selectInvert = () => {
    let totalArr = [];
    const list = checkedList;
    const optlist = checkboxes;
    if (checkedList.length == checkboxes.length) {
      setCheckedList([]);
      return
    }
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < optlist.length; j++) {
        if (list[i] === optlist[j].value) {
          list.splice(i, 1)
        } else {
          totalArr = totalArr.concat(optlist[j].value)
        }
      }
    }
    setCheckedList(totalArr)
  }

  //批量或者单条放行消息
  const passMsg = () => {
    if (!checkedList || checkedList.length <= 0) return;
    emitter.next(checkedList);
  }

  //获取最新的分页数据
  useEffect(() => {
    const subscriptions: Subscription[] = [
      msgsFacade.pagination$
        .pipe(
          tap(pagination => {
            //定义一个初始数组
            let optionArr: CheckboxOption<any>[] = [];
            pagination.data && pagination.data.length > 0 && pagination.data.map(item => {
              const option = { value: item.id, label: item.nick || item.from, desc: item.body[0].MsgContent.Text } as CheckboxOption<any>
              optionArr = optionArr.concat(option);
            })
            setCheckboxes(optionArr);
          })
        )
        .subscribe(),

      //定时拉取最新消息
      interval(2000)
        .pipe(
          tap(() => {
            //定时拉取最新聊天信息
            msgsFacade.refreshPage();
          }),
        )
        .subscribe()
    ]

    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  //监听按钮点击
  useEffect(() => {
    const sub = emitter.asObservable()
      .pipe(
        debounceTime(500), //防重复点击
        map(ids => ids as string[]),
        switchMap(ids => {
          Taro.showLoading({
            title: '处理中...',
            mask: true,
          })

          return msgsFacade.passPendingMsg(ids)
            .pipe(
              tap(() => {
                Taro.hideLoading();
                setCheckedList([]);
                arrayRemove(checkboxes, item => ids.includes(item.value.id))
              })
            )
        })
      )
      .subscribe(
        console.log,
        () => setEmitter(initSubject)
      )

    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => sub.unsubscribe();
  }, [emitter, checkboxes]);

  usePullDownRefresh(() => {
    console.log('onPullDownRefresh') 
    setCheckedList([]);
    //上拉获取翻页记录
    msgsFacade.prevPage();
    Taro.stopPullDownRefresh() 
  })

  useReachBottom(() => {
    console.log('onReachBottom');
    setCheckedList([]);
    //上拉获取翻页记录
    msgsFacade.nextPage();
  })

  useReady(() => {
    Taro.showToast({
      title: '可以在屏幕上下划动以拉取最新消息',
      icon: 'none',
      duration: 5000
    })
  })

  return (
    <View className='index'>
      <View className='main'>
        <AtCheckbox
          options={checkboxes}
          selectedList={checkedList}
          onChange={handleChange.bind(this)}
        />
      </View>
      <View className='foot'>
        <View className='foot-left'>
          <View className='checkAll' onClick={selectAll}>全选</View>
          <View className='notCheck' onClick={selectInvert}>反选</View>
        </View>
        <View className='foot-right' onClick={passMsg}>放行({checkedList.length}/10)</View>
      </View>
    </View>
  )
}
export default ChatLIst